import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/Home/MyHome.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/login',
    name: 'login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Login/MyLogin.vue')
  },
  {
    path: '/detail',
    name: 'detail',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Detail/MyDetail.vue')
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About/MyAbout.vue')
  },
  {
    path: '/cart',
    name: 'cart',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Cart/MyCart.vue'),
    meta: { requiresAuth: true }//标记该路由需要权限验证
  },
  {
    path: '/order',
    name: 'order',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/Order/MyOrder.vue'),
    meta: { requiresAuth: true }//标记该路由需要权限验证
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token'); //检查localStorage中是否存在token，存在则认为已登录
  const targetLocation = from.fullPath; //存储重定向目标
 
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      // 如果用户未登录且尝试访问受保护的页面
      // 存储重定向目标（可以存储在 Vuex 或查询参数中）
      // 这里简单存储在 sessionStorage 中
      sessionStorage.setItem('redirectTarget', targetLocation);
      next({
        path: '/login',
        query: { redirect: targetLocation } //将目标页面地址作为查询参数传递给登录页面,也可以作为查询参数传递
      });
    } else {
      next(); // 用户已登录，继续导航
    }
  } else {
    next(); // 路由不需要权限，继续导航
  }
});

export default router
